/**
 * @modal: 手动合单
 */
import { useState, useEffect, useRef, useMemo  } from 'react';
import { Alert, Row, Button, message } from 'antd';
import { find } from 'lodash';
import CommonLoading from '@/components/CommonLoading';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import { CommonTable } from '@/pages/OrderModule/common/components/CommonTable';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { useGoodsColumns } from './goodsColumns';
import OrderDetailModal from '../OrderDetailModal';
import { waitMergeOrders, manualMergeOrderOp } from '../../../../services';
import Style from './index.module.less';

function MergeOrdersModal({ selectKeys, orderList, handleOk, handleCancel }) {
  const [goodsDetailVisible, setGoodsDetailVisible] = useState(false);
  const { goodsColumns } = useGoodsColumns({
    handleOpenOrderDetail: () => {
      setGoodsDetailVisible(true);
    },
  });

  const [data, setData] = useState([]);
  const [loading, setLoading]=useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const currentOrder = useRef({});

  const { id: mainOrderId } = currentOrder.current;

  useEffect(()=>{
    formatGoodsList();
  },[])

  const waitMergeOrderIds = useMemo(()=>{
    return selectedRowKeys.filter(item=>item != mainOrderId);
  }, [selectedRowKeys])

  //缓存主订单数据
  const formatGoodsList = () => {
    const order = find(orderList, ['id', selectKeys[0]]);
    if(order){
      currentOrder.current = order;
      getFieldsFunc();
    }
  }

  // 获取待合单数据
  const getFieldsFunc = async () => {
    setLoading(true);
    const { data, success} = await waitMergeOrders({ orderId: currentOrder.current.id });
    setLoading(false);
    if(success){
      setData([{
        ...currentOrder.current,
        mainOrder: true
      }, ...(data || [])]);
    }
  }

  //手动合单
  async function handleSave() {
    if(!waitMergeOrderIds?.length){
      return message.info('请勾选需要合并的订单');
    }
    const { data, success } = await manualMergeOrderOp({ mainOrderId, waitMergeOrderIds });
    if(success){
      message.success('合单成功');
      handleOk?.(3, data);
      handleCancel?.();
    }
  }

  const modalFooter = [
    <Button onClick={handleCancel}>取消</Button>,
    <Button type="primary" onClick={handleSave}>
      确定合单
    </Button>,
  ];

  return (
    <>
      {goodsDetailVisible && <OrderDetailModal onCancel={() => setGoodsDetailVisible(false)} />}
      <CommonModal title={{ title: '手动合单' }} open={true} footer={modalFooter} width="1209px" onCancel={handleCancel} onOk={handleSave}>
        <Alert showIcon message={<Typography as="s1">系统会读取跟主订单，同一店铺+买家账号、并且收货信息完全一致的订单</Typography>} />
        <CommonTable
          className={Style.order_item_table}
          scroll={{ y: `calc(100vh - 250px)` }}
          columns={goodsColumns}
          rowSelection={{
            selectedRowKeys,
            onChange: (selectedRowKeys) => {
              setSelectedRowKeys(selectedRowKeys);
            },
          }}
          dataSource={data}
          rowKey='id'
          pagination={false}
          rowClassName={(a, index) =>`hideFirstTableCell${index}`}
        />
        <Row className={Style.tips}>
          <Typography as="s1">已选订单数：{waitMergeOrderIds.length}</Typography>
        </Row>
      </CommonModal>
      <CommonLoading loading={loading} />
    </>
  );
}

export default MergeOrdersModal;
